package util;

import com.alibaba.fastjson.JSONArray;

import java.util.List;

public class Condition {
    /**
     * 只有带参数构造器，防止JSON调用无参构造器
     * @param key 属性名
     * @param operator 操作符
     * @param value 属性值
     */
    public Condition(String key,String operator,String value){
        this.key = key;
        this.operator = operator;
        this.value = value;
    }

    /**
     * 根据前台的请求为findAll方法的sql语句构建where判定
     * @param condition_json 前台传来的请求，json格式
     * @return
     */
    public static String toWhereClause(String condition_json){
        //将json格式字串解析为Condition的集合
        List<Condition> conditions = JSONArray.parseArray(condition_json.toString(), Condition.class);
        //构建where语句
        StringBuilder where_sql = new StringBuilder(" WHERE ");
        //在where后添加判定
        for (Condition condition : conditions){
            //添加属性值和操作符
            where_sql.append(condition.getKey()).append(" ").append(condition.getOperator()).append(" ");
            //获得condition对应属性名的值
            String sql_value = condition.getValue();
            //如果操作符为like则在前后加%来模糊查询
            if ("like".equalsIgnoreCase(condition.getOperator())){
                sql_value = "%" + sql_value + "%";
            }
            //将值用引号括起来
            sql_value = " \"" + sql_value + "\" ";
            //将值添加到sql语句后面
            where_sql.append(sql_value);
            //添加AND
            where_sql.append(" AND ");
        }
        //删除掉最后一个AND
        TxtHelper.truncEnding(where_sql,5);
        return where_sql.toString();
    }
    public String getKey(){
        return this.key;
    }
    public String getOperator(){
        return this.operator;
    }
    public String getValue(){
        return this.value;
    }
    //属性名
    private String key;
    //操作符
    private String operator;
    //属性值
    private String value;
    //where key operator value and/or  ....  name like "%A%"
}
